<template>
  <!-- 登录页面容器 -->
  <div class="login-container">
    <!-- 登录表单 -->
    <el-form :model="form" :rules="rules" ref="formRef" class="login-form">
      <!-- 用户名输入框 -->
      <el-form-item label="用户名" prop="name">
        <el-input v-model="form.name" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <!-- 密码输入框 -->
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <!-- 登录按钮 -->
      <el-form-item>
        <el-button :loading="loading" type="primary" @click="handleSubmit">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
// 导入所需的模块和函数
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { login } from '@/api/admin';
import { useTokenStore } from '@/stores/token';

// 定义表单数据
const form = ref({
  name: '',
  password: ''
});

// 获取token存储实例
const uts = useTokenStore();

// 定义表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};

// 获取表单引用和加载状态
const formRef = ref(null);
const loading = ref(false);

// 获取路由实例
const router = useRouter();

// 处理表单提交
const handleSubmit = async () => {
  loading.value = true;
  try {
    // 验证表单
    await formRef.value.validate();
    // 发送登录请求
    const response = await login(form.value);
    if (response.shuju) {
      ElMessage.success('登录成功');
      console.log('登录成功', response.shuju);
      // 保存token
      uts.setToken(response.shuju)
      // 跳转到商户页面
      router.push('/merchant');
    } else {
      throw new Error('登录失败，请检查用户名和密码');
    }
  } catch (error) {
    console.error('请求出错', error);
    ElMessage.error(error.message || '登录请求出错');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-form {
  width: 400px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
